import React, { useState } from 'react';
import { Modal, Transfer } from 'antd';
import { TransferDirection } from 'antd/lib/transfer';
import { FormModalProps } from '@/types/global';
import { AssignUserRoleData } from '@/types/user';

type AssignRoleProps<T> = FormModalProps<T> & {
}

const AssignRoleModal: React.FC<AssignRoleProps<AssignUserRoleData>> = (props) => {

  const [targetKeys, setTargetKeys] = useState<string[]>([]);

  const onOk = () => {
    const { onHandlerOK } = props;
    if (onHandlerOK) {
      const { formData } = props;
      const { userId } = formData;
      const submitData = {
        userId,
        roleIds: [...targetKeys]
      }
      onHandlerOK({
        ...submitData
      });
    }
  };

  const onCancel = () => {
    const {onHandlerCancel} = props;
    // 先清除form表单
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  const onChange = (targetKeys: string[], direction: TransferDirection, moveKeys: string[]) => {
    console.log('targetKeys:', targetKeys);
    console.log('direction:', direction);
    console.log('moveKeys:', moveKeys);
    // setTargetKeys(nextTargetKeys);
    setTargetKeys(targetKeys);
  };

  const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
    console.log('sourceSelectedKeys:', sourceSelectedKeys);
    console.log('targetSelectedKeys:', targetSelectedKeys);
    // setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  const { formData, modalWidth, modalVisible, modalTitle, loading } = props;
  const { allRoleData, assignedRoleData } = formData;
  // 处理已分配角色的问题
  // 如果 assignedRoleData 有值，则不看 state 中的 targetKeys
  // 如果 assignedRoleData 没有值，则看 state 中的 targetKeys
  let tmpTargetKeys: string[] = [];
  // 优先看 checkedKeys
  if (targetKeys && targetKeys.length > 0) {
    tmpTargetKeys = [...targetKeys];
  } else if (assignedRoleData && assignedRoleData.length > 0) {
    tmpTargetKeys = [...assignedRoleData];
    // 若子节点全部存在，则父节点会自动勾选
    // tmpCheckedKeys.push('23');
    // tmpCheckedKeys.push('24');
    // tmpCheckedKeys.push('25');
    // tmpCheckedKeys.push('31');
  } else {
    // tmpCheckedKeys = [...checkedKeys];
  }

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Transfer
        dataSource={allRoleData}
        titles={['全部角色', '已分配角色']}
        targetKeys={tmpTargetKeys}
        render={item => item.title}
        pagination
        onChange={onChange}
        onSelectChange={onSelectChange}
      />
    </Modal>
  );
}

export default AssignRoleModal